import { getAccountInfo } from '@/models/ApiService';
import notify from 'devextreme/ui/notify';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';
export default function Page() {
  const globalModel = useModel('@@initialState') as any;

  const dbname = globalModel?.initialState?.curPart?.dbname;

  const [dataList, setDataList] = useState<any[]>([]);

  const lastRefDataList = useRef<any[]>(['init']);

  /**
   * 获取账套年度数据
   */
  const ztDates = useMemo(() => {
    return dataList.map((item) => {
      return item.ND;
    });
  }, [dataList]);

  const getDefaultValue = useCallback(() => {
    if (dataList.length > 0) {
      return dataList[dataList.length - 1].Data_ID;
    }
  }, [dataList]);

  const defaultValue = getDefaultValue();

  const refresh = useCallback(async () => {
    if (dbname) {
      // getAccountInfo({ dbname: dbname })
      //   .then((responseData: any) => {
      //     const ztList = responseData.data;
      //     const isArray = Array.isArray(responseData.data);
      //     if (isArray) {
      //       // 进行数组对比
      //       if (JSON.stringify(ztList) !== JSON.stringify(lastRefDataList.current)) {
      //         setDataList(ztList);
      //         lastRefDataList.current = ztList;
      //       }
      //       console.log('@@@', ztList);

      //       debugger;
      //       return ztList;
      //     } else {
      //       notify(`获取账套信息异常!`, 'error', 2000);
      //       return [];
      //     }
      //   })
      //   .catch((error) => {
      //     console.error(error);
      //     notify(`获取账套信息异常!`, 'error', 2000);
      //     return [];
      //   });

      try {
        const responseData: any = await getAccountInfo({ dbname: dbname });
        if (responseData.success) {
          const ztList = responseData.data;
          // 进行数组对比
          if (JSON.stringify(ztList) !== JSON.stringify(lastRefDataList.current)) {
            setDataList(ztList);
            lastRefDataList.current = ztList;
          }
          console.log('@@@', ztList);
          return ztList.map((item: any) => item.ND);
        }
        return [];
      } catch (error) {
        console.error(error);
        notify(`获取账套信息异常!`, 'error', 2000);
        return [];
      }
    }
  }, [dbname]);

  useEffect(() => {
    refresh();
  }, [dbname, refresh]);

  return {
    dataList,
    defaultValue,
    getDefaultValue,
    refresh,
    ztDates,
  };
}
